package com.fastCms.business.frame.busi.impl;

import cn.hutool.core.util.StrUtil;
import com.fastCms.business.frame.busi.CloudMenuManageService;
import com.fastCms.business.frame.busi.CloudUserManageService;
import com.fastCms.business.frame.busi.RedisCloudUserModelManager;
import com.fastCms.business.frame.constant.CommonConst;
import com.fastCms.business.frame.constant.ResultCodeConst;
import com.fastCms.business.frame.daos.CloudUserMapper;
import com.fastCms.business.frame.daos.CloudUserRoleRelMapper;
import com.fastCms.business.frame.enums.*;
import com.fastCms.business.frame.exception.BusinessException;
import com.fastCms.business.frame.pojo.CloudUserModel;
import com.fastCms.business.frame.pojo.PageParam;
import com.fastCms.business.frame.pojo.entity.CloudUser;
import com.fastCms.business.frame.pojo.entity.CloudUserRoleRel;
import com.fastCms.business.frame.pojo.po.*;
import com.fastCms.business.frame.pojo.vo.CloudMenuVO;
import com.fastCms.business.frame.pojo.vo.CloudUserVO;
import com.fastCms.business.frame.response.ApiResponse;
import com.fastCms.business.frame.response.ResponseUtil;
import com.fastCms.business.frame.service.CloudRoleService;
import com.fastCms.business.frame.service.CloudUserRoleRelService;
import com.fastCms.business.frame.service.CloudUserService;
import com.fastCms.business.frame.utils.CommonsUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 哈密瓜科技 版权所有 © Copyright 2019<br>
 *
 * @Description: 登录权限控制<br>
 * @Project: hami <br>
 * @CreateDate: Created in 2019/3/7 下午3:48 <br>
 * @Author: <a href="lsquan666@163.com">lsquan</a>
 */
@Component
@Transactional
@Slf4j
public class CloudUserManageServiceImpl implements CloudUserManageService {
    @Resource
    private CloudUserService cloudUserServiceImpl;

    @Autowired
    private CloudMenuManageService cloudMenuManageServiceImpl;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CloudUserRoleRelService cloudUserRoleRelServiceImpl;

    @Autowired
    private CloudUserRoleRelMapper cloudUserRoleRelMapper;

    @Autowired
    private CloudRoleService cloudRoleServiceImpl;

    @Autowired
    private RedisCloudUserModelManager redisCloudUserModelManagerImpl;

    @Autowired
    private CloudUserMapper cloudUserMapper;

    @Override
    public ApiResponse<CloudUserModel> loginAuth(CloudLoginUserPO param, HttpServletRequest request) {
        String username = param.getUsername();
        String password = param.getPassword();
        //TODO 上线时改成加密
        // String password = new Md5Hash(userInfo.getPassword(), CommonConst.USER_MANAGER.PWD_PRIVATE_KEY, 1024).toBase64();
        CloudUser cloudUser = null;
        if (param.getType() == 1) {
            cloudUser = cloudUserServiceImpl.findByUsername(username, param.getPlatform());
        } else if (param.getType() == 1) {
            cloudUser = cloudUserServiceImpl.findByPhone(username, param.getPlatform());
        } else {
            return ResponseUtil.fail(ResultCodeConst.USER.USER_NOT_EXIST, "错误登录方式");
        }
        //1.验证用户是否存在
        if (cloudUser == null) {
            return ResponseUtil.fail(ResultCodeConst.USER.USER_NOT_EXIST, ResultCodeConst.USER.USER_NOT_EXIST_MSG);
        }
        //2.用户类型验证
        if (!cloudUser.getPlatform().equals(param.getPlatform())) {
            return ResponseUtil.fail(ResultCodeConst.USER.USER_PLATFORM_ERROR, ResultCodeConst.USER.USER_PLATFORM_ERROR_MSG);
        }
        //3.用户密码正确性
        if (!StringUtils.equals(password, cloudUser.getPassword())) {
            return ResponseUtil.fail(ResultCodeConst.USER.USER_OR_PWD_ERROR, ResultCodeConst.USER.USER_OR_PWD_ERROR_MSG);
        }
        //4.验证用户状态
        if (null != cloudUser.getStatus() && cloudUser.getStatus() != 1) {
            return ResponseUtil.fail(ResultCodeConst.USER.USER_STATUS_ERROR, ResultCodeConst.USER.USER_STATUS_ERROR_MSG);
        }

        //5.用户模型
        CloudUserModel model = redisCloudUserModelManagerImpl.createToken(UserTypeEnum.CLOUD_USER, cloudUser.getId());
        model.setUsername(cloudUser.getUsername());
        model.setPlatform(cloudUser.getPlatform());

        //6.用户类型
        if (cloudUser.getPlatform().equals(PlatformEnum.CMS.getCode()) || cloudUser.getPlatform().equals(PlatformEnum.ADMIN.getCode())) {
            //菜单权限
            BeanUtils.copyProperties(cloudUser, model);
            model.setUserId(cloudUser.getId());
            Integer adminType = cloudUser.getAdminType();

            String superOrganizeCode = "SUPER";
            if (adminType == CloudAdminTypeEnum.SUPER_ADMIN.getCode()) {  //如果为超管
                //查询超管拥有的菜单
                List<CloudMenuVO> superAdminMenu = cloudMenuManageServiceImpl.findSuperAdminMenu(superOrganizeCode);
                model.setCloudMenus(superAdminMenu);

            } else if (adminType == CloudAdminTypeEnum.SYSTEM_ADMIN.getCode()) { //如果为系统管理员
                List<CloudMenuVO> systemAdminMenu = cloudMenuManageServiceImpl.findSystemAdminMenu(cloudUser.getOrganizeCode(), MenuFunctionTypeEnum.MENU.getType());
                model.setCloudMenus(systemAdminMenu);

            } else if (adminType == CloudAdminTypeEnum.SYSTEM_USER.getCode()) {//如果为系统用户

                CloudUserRoleRel cloudUserRoleRel = cloudUserRoleRelServiceImpl.findByUserId(cloudUser.getId());
                if (cloudUserRoleRel == null) {
                    return ResponseUtil.fail(ResultCodeConst.USER.USER_NOT_EXIST, ResultCodeConst.USER.USER_NOT_EXIST_MSG);
                }
                List<CloudMenuVO> systemUserMenu = cloudMenuManageServiceImpl.findSystemUserMenu(cloudUserRoleRel.getRoleId(), MenuFunctionTypeEnum.MENU.getType());
                model.setCloudMenus(systemUserMenu);
            }
        }
        redisCloudUserModelManagerImpl.saveRedisToken(UserTypeEnum.CLOUD_USER, model);
        return ResponseUtil.success(model);
    }

    @Override
    public ApiResponse<CloudUser> addCloudUser(AddCloudUserPO cloudUserPO) throws BusinessException {
//        String roleId = cloudUserPO.getRoleId();
//        //1.根据角色查询
//        CloudRole cloudRole = cloudRoleServiceImpl.findByRoleId(roleId);
//        if (cloudRole == null) {
//            log.error("根据roleId=" + roleId + " ,查询-----error---,cloudRole = null-------");
//            return ResponseUtil.fail(ResultCodeConst.DATA_ERROR_MSG);
//        }
        Boolean hasLoginType = false;
        //2.校验:用户名是否存在
        if (StrUtil.isNotBlank(cloudUserPO.getUsername())) {
            CloudUser cloudUser = cloudUserServiceImpl.findByUsername(cloudUserPO.getUsername(), PlatformEnum.CMS.getCode());
            if (cloudUser != null) {
                return ResponseUtil.fail(ResultCodeConst.USER.PHONE_BE_REGISTER, ResultCodeConst.USER.PHONE_BE_REGISTER_MGS);
            }
            hasLoginType = true;
        }

        //3.校验:手机号是否存在
        if (StrUtil.isNotBlank(cloudUserPO.getPhone())) {
            CloudUser cloudUser = cloudUserServiceImpl.findByPhone(cloudUserPO.getPhone(), PlatformEnum.CMS.getCode());
            if (cloudUser != null) {
                return ResponseUtil.fail(ResultCodeConst.USER.PHONE_BE_REGISTER, ResultCodeConst.USER.PHONE_BE_REGISTER_MGS);
            }
            hasLoginType = true;
        }
        if (!hasLoginType) {
            return ResponseUtil.fail(ResultCodeConst.PARAM_ERROR, "手机号或用户名必填其中一个");
        }

        CloudUser cloudUser = new CloudUser();
        //3.创建用户名和初始密码
//        cloudUser.setPassword(CommonsUtil.getInitEncryptPwd());
        cloudUser.setPassword(CommonConst.USER_MANAGER.INIT_PASSWORD);
        cloudUser.setStatus(AccountStatusEnum.CAN_USE.getCode());

        //4.创建用户
        CommonsUtil.initEntity(cloudUser);
        cloudUser.setAdminType(CloudAdminTypeEnum.SYSTEM_USER.getCode()); //非管理员-需要换枚举
        cloudUser.setName(cloudUserPO.getName());
        cloudUser.setPhone(cloudUserPO.getPhone());
        cloudUser.setPlatform("CMS");
        cloudUser.setOrganizeCode(cloudUserPO.getOrganizeCode());
        cloudUser.setEmail(cloudUserPO.getEmail());
        cloudUser.setUsername(cloudUserPO.getUsername());
        cloudUser.setHeadImg(cloudUserPO.getHeadImg());

        boolean userResult = cloudUserServiceImpl.save(cloudUser);

//        //5.绑定用户和角色的关系
//        CloudUserRoleRel relation = new CloudUserRoleRel();
//        CommonsUtil.initEntity(relation);
//
//        relation.setRoleId(roleId);
//        relation.setUserId(cloudUser.getId());
//        boolean relationResult = cloudUserRoleRelServiceImpl.save(relation);

        if (userResult) {
            return ResponseUtil.success(cloudUser);
        }
        return ResponseUtil.fail(ResultCodeConst.FAIL_MSG);
    }

    @Override
    public ApiResponse deleteCloudUser(String userId) {

        //1.删除用户
        CloudUser cloudUser = cloudUserServiceImpl.findById(userId);
        if (cloudUser == null) {
            return ResponseUtil.fail(ResultCodeConst.DATA_ERROR, ResultCodeConst.DATA_ERROR_MSG);
        }
        if (cloudUser.getAdminType() != CloudAdminTypeEnum.SYSTEM_USER.getCode()) {
            return ResponseUtil.fail(ResultCodeConst.USER.NO_AUTH, ResultCodeConst.USER.NO_AUTH_MSG);
        }

        //2.删除用户与角色关联关系
        int a = cloudUserRoleRelMapper.deleteByUserId(userId);
        cloudUser.setState(CommonConst.STATE.INVALID);
        Boolean b = cloudUserServiceImpl.saveOrUpdate(cloudUser);
        if (a != 0 && b) {
            return ResponseUtil.success(true);
        }
        return ResponseUtil.fail(ResultCodeConst.DATA_ERROR, ResultCodeConst.DATA_ERROR_MSG);
    }

    @Override
    public ApiResponse<CloudUser> updateCloudUser(UpdateCloudUserPO updateCloudUserPO) {
        //2.删除用户
        CloudUser cloudUser = cloudUserServiceImpl.findById(updateCloudUserPO.getUserId());
        if (cloudUser == null) {
            return ResponseUtil.fail(ResultCodeConst.DATA_ERROR, ResultCodeConst.DATA_ERROR_MSG);
        }

        //变更手机号
        if (StringUtils.isNotBlank(updateCloudUserPO.getPhone()) &&
                StrUtil.equals(cloudUser.getPhone(), updateCloudUserPO.getPhone())) {
            Boolean result = cloudUserServiceImpl.isCanChangeNewPhone(updateCloudUserPO.getUserId(), cloudUser.getPhone());
            if (!result) {
                return ResponseUtil.fail(ResultCodeConst.DATA_ERROR, "手机号" + cloudUser.getPhone() + "已被占用,请更换");
            }
            cloudUser.setPhone(updateCloudUserPO.getPhone());
        }
        cloudUser.setName(updateCloudUserPO.getName());
        cloudUser.setHeadImg(updateCloudUserPO.getHeadImg());
        cloudUser.setEmail(updateCloudUserPO.getEmail());
        cloudUser.setIntroduction(updateCloudUserPO.getIntroduction());
        Boolean b = cloudUserServiceImpl.saveOrUpdate(cloudUser);
        return ResponseUtil.success(b);
    }

    @Override
    public ApiResponse resetPwd(UserResetPwdPO resetPwdPO) {

        CloudUser cloudUser = cloudUserServiceImpl.getById(resetPwdPO.getUserId());
        if (cloudUser == null) {
            return ResponseUtil.fail(ResultCodeConst.USER.USER_NOT_EXIST, ResultCodeConst.USER.USER_NOT_EXIST_MSG);
        }
        String oldPwd = new Md5Hash(resetPwdPO.getOldPassword(), CommonConst.USER_MANAGER.PWD_PRIVATE_KEY, 1024).toBase64();
        if (!cloudUser.getPassword().equals(oldPwd)) {
            return ResponseUtil.fail(ResultCodeConst.USER.USER_OR_PWD_ERROR, ResultCodeConst.USER.USER_OR_PWD_ERROR_MSG);
        }
        String newPwd = new Md5Hash(resetPwdPO.getNewPassword(), CommonConst.USER_MANAGER.PWD_PRIVATE_KEY, 1024).toBase64();
        cloudUser.setPassword(newPwd);
        cloudUser.setUpdateBy(resetPwdPO.getUserId());
        cloudUserServiceImpl.saveOrUpdate(cloudUser);

        return ResponseUtil.success(true);
    }

    @Override
    public ApiResponse<PageInfo<CloudUserVO>> showPage(PageParam<CloudUserPO> pageParam) {
        CloudUserPO queryFields = pageParam.getQueryFields();
        PageInfo<CloudUserVO> result =
                PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize())
                        .doSelectPageInfo(() ->
                                cloudUserMapper.showList(queryFields)
                        );
        return ResponseUtil.success(result);
    }

    @Override
    public ApiResponse<CloudUser> useRelRole(CloudUserRelRolePO param) {
        String userId = param.getUserId();
        String roleId = param.getRoleId();
        CloudUserRoleRel cloudUserRoleRel = cloudUserRoleRelServiceImpl.findByUserId(userId);
        if (null != cloudUserRoleRel) {
            cloudUserRoleRel.setRoleId(roleId);
        } else {
            cloudUserRoleRel = new CloudUserRoleRel();
            CommonsUtil.initEntity(cloudUserRoleRel);
            cloudUserRoleRel.setUserId(userId);
            cloudUserRoleRel.setRoleId(roleId);
        }
        cloudUserRoleRelServiceImpl.saveOrUpdate(cloudUserRoleRel);
        return ResponseUtil.success(true);
    }

    @Override
    public ApiResponse<Boolean> changeStatus(CloudUserEditStatusPO param) {

        //1.删除用户
        CloudUser cloudUser = cloudUserServiceImpl.findById(param.getUserId());
        if (cloudUser == null) {
            return ResponseUtil.fail(ResultCodeConst.DATA_ERROR, ResultCodeConst.DATA_ERROR_MSG);
        }
        if (cloudUser.getAdminType() != CloudAdminTypeEnum.SYSTEM_USER.getCode()) {
            return ResponseUtil.fail(ResultCodeConst.USER.NO_AUTH, ResultCodeConst.USER.NO_AUTH_MSG);
        }

        cloudUser.setStatus(param.getStatus());
        cloudUserServiceImpl.updateById(cloudUser);
        return ResponseUtil.success(true);
    }

}
